//
//  PersonalInfoViewController.m
//  shopping
//
//  Created by 徐双 on 2017/9/4.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "FS_MyChangrSexViewController.h"

#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "UIButton+AddAction.h"
#import "ICN_HeadImageSelView.h"
#import "personChangePhoneViewController.h"

@interface PersonalInfoViewController ()<UIImagePickerControllerDelegate,STPhotoKitDelegate,UINavigationControllerDelegate,numDelegate,UITextFieldDelegate>
{


    UIView *grayView;
    NSString *sexaa;
    NSString *usrID;
    NSString *riQi;
}
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
@property (weak, nonatomic) IBOutlet UIButton *imgButton;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *shoujiTF;
@property (weak, nonatomic) IBOutlet UITextField *timeField;


@property (weak, nonatomic) IBOutlet UIImageView *imgHead;
@property (nonatomic, strong) NSMutableDictionary *productParamsss;

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSData *imageData;

@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong) UIDatePicker *dataPick;

@property (strong, nonatomic) UIDatePicker *dateKB;// 日期键盘

@property (nonatomic, strong) ICN_HeadImageSelView *changeHeadImageView;


@end

@implementation PersonalInfoViewController

- (void)viewWillAppear:(BOOL)animated{
    
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setTitle:@"个人信息"];
    [self creationData];
    [self creationView];
    self.nameTF.enabled = NO;
    self.shoujiTF.delegate = self;
    self.shoujiTF.enabled = NO;
    
 //   _shoujiTF.keyboardType = UIKeyboardTypeNumberPad;

    self.timeField.delegate = self;
 //   self.timeField.enabled = NO;
    
    
}
- (void)creationView{

    self.imgHead.layer.cornerRadius = 25.0f;
    self.imgHead.layer.masksToBounds = YES;
    UIButton *buttonAdd = [[UIButton alloc] init];
    
    buttonAdd.frame = CGRectMake(DEF_SCREEN_WIDTH - 40, 0, 40, 40);
    
    
    [buttonAdd setTitle:@"保存" forState:UIControlStateNormal];
    
    [buttonAdd addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    [buttonAdd setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc]initWithCustomView:buttonAdd];
    self.navigationItem.rightBarButtonItem = rightItme;
    
    // 初始化日期键盘
    self.dateKB = [UIDatePicker new];
    _dateKB.datePickerMode = UIDatePickerModeDate; // 设置模式 这里是 年月日 没有上下午
    _dateKB.locale = [NSLocale localeWithLocaleIdentifier:@"zh"]; // 设置地区 这里是
    self.timeField.inputView = _dateKB; // 用 UIDatePicker 替换 timeField 的键盘
    
    // 当值改变的时候会触发的方法  我们滑动日期键盘的时候  执行方法 rollAction:
    [_dateKB addTarget:self action:@selector(rollAction:) forControlEvents:(UIControlEventValueChanged)];

    
    

}
#pragma mark ------>> 使用键盘的代理方法对输入进行控制 监听的效果 <<------
//// 这里返回 NO 就是不让键盘输入  而是按照我们需要的作为 textFile 的 text
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    NSLog(@"方法名--->%s", __func__);
//    return NO;
//}
#pragma mark 开始编辑的时候就把默认的 日期 和地址 显示上  可以直接调用方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"方法名--->%s", __func__);
    if (textField == self.timeField)
    {// 调用 PickView 的选中方法 给地址 textFile 赋值 (这个方法在后面有)
        [self rollAction:_dateKB];
    }
    
}

#pragma mark ------>> 监听滚动的方法   滚动日期键盘时候走的方法<<------
- (void)rollAction:(UIDatePicker *)sender
{
    // 格式化日期格式
    NSDateFormatter *formatter = [NSDateFormatter new];
    // 设置显示的格式     这里的格式 2016 / 08 / 08
    [formatter setDateFormat:@"YYYY / MM / dd"];
    // UIDatePicker 滚动也就是日期改变 我们就改变对应的 textFile 的 text
    self.timeField.text = [formatter stringFromDate:sender.date];
    
}

- (void)creationData{

    _dataDic = [[NSMutableDictionary alloc] init];
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    // NSString *token = @"32728a411b83e29b9836262a72477e3e0dac";
    
    [productParams setValue:token forKey:@"token"];
    [[MNetworkHandler sharedInstance]conURL:adminLxlpersonupdate networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        if ([[returnData objectForKey:@"status"]intValue]==1) {
            
            self.dataDic = [returnData objectForKey:@"data"];
            
            self.nameTF.text = [self.dataDic objectForKey:@"loginName"];
            self.shoujiTF.text = [self.dataDic objectForKey:@"userPhone"];
            self.timeField.text = [self.dataDic objectForKey:@"birthday"];
             
            
            usrID = [self.dataDic objectForKey:@"userId"];
            if ([[self.dataDic objectForKey:@"userSex"] isEqualToString:@"1"]) {
                self.sexLabel.text = @"男";
            }else {
            
                self.sexLabel.text = @"女";
            }
//            NSString *urlWare=[self.dataDic objectForKey:@"userPhoto"];
//            NSString *urlN=manage(AP_Img, urlWare);
//            
//            [self.imgHead sd_setImageWithURL:[NSURL URLWithString:urlN] placeholderImage:[UIImage imageNamed:@"geren_touxiang"]];
            
            NSString *urlN=manage(AP_HOST, [self.dataDic objectForKey:@"userPhoto"]);
            NSLog(@"%@", urlN);
            [self.imgHead sd_setImageWithURL:[NSURL URLWithString:urlN] placeholderImage:[UIImage imageNamed:@"geren_touxiang"]];
            
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
//        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        
    }];

    
    
    
}

//保存
- (void)sureClick{

//    NSString *token = [PublicFunction getConfigWithKey:@"token"];
//    [self.productParamsss setValue:token forKey:@"token"];
    self.productParamsss = [[NSMutableDictionary alloc] init];
    
    if([TSRegularExpressionUtil validateMobile:_shoujiTF.text] == NO ){
        
        [PublicFunction showAlert:nil message:@"请输入正确格式的手机号码" duration:1.0];
        return;
    }
    
    
    [self.productParamsss setValue:usrID forKey:@"userId"];
    [self.productParamsss setValue:self.shoujiTF.text forKey:@"userPhone"];
 //   [self.productParamsss setValue:self.nameTF.text forKey:@"userName"];

    [self.productParamsss setValue:self.timeField.text forKey:@"birthday"];
    
    if ([self.sexLabel.text isEqualToString:@"男"]) {
        sexaa = @"1";
    }else {
        
        sexaa = @"2";
    }
    
    [self.productParamsss setValue:sexaa forKey:@"userSex"];
    //    [self.productParams setValue:self.image forKey:@"pic"];
    
    
    //两种方式上传头像
    /*方式一：使用NSData数据流传图片*/
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg", nil];
    [manager POST:adminLxlpersonupdatedo parameters:self.productParamsss constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (self.image) {
            
            self.imageData = UIImageJPEGRepresentation(self.image,0.005);
        }else {
            
            
            self.imageData = UIImageJPEGRepresentation(self.imgHead.image,0.005);
            
        }
        
        
        //压缩图片
        
        //拼接图片名称+时间确保不重复命名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *imageFileName = [NSString stringWithFormat:@"%@.jpg", [formatter stringFromDate:[NSDate date]]];
        // 测试输出文件名
        
        //上传图片，以文件流的格式sdf
        
        //        [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"1"], 5.0) name:@"image1" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        
        [formData appendPartWithFileData:_imageData name:@"userPhoto" fileName:imageFileName mimeType:@"image/JPG"];

        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
        
        if ([[resultDic objectForKey:@"code"] intValue] == 1) {
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else {
        
             [PublicFunction showAlert:nil message:[resultDic objectForKey:@"msg"] duration:5.0f];
        }
        
        
        
        NSLog(@"+++>%@", resultDic);
        
        NSLog(@"--->%@", resultDic[@"msg"]);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"--->%@", error);
    }];

    
}
- (void)getNum:(NSString *)sex{
    
    self.sexLabel.text = sex;
    
    
}
//选择性别
- (IBAction)sexClick:(UIButton *)sender {
    FS_MyChangrSexViewController *vc = [[FS_MyChangrSexViewController alloc] init];
    vc.sexNum = self.sexLabel.text;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
//选择头像
- (IBAction)imgClick:(UIButton *)sender {
    
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    
    [grayView addSubview:self.changeHeadImageView];
    [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 160));
    }];
    
    self.changeHeadImageView.layer.cornerRadius = 8;
    [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        [grayView removeFromSuperview];
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        [grayView removeFromSuperview];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
        [self dismissContactView];
    }];

    
}
#pragma mark ----------------------- 相册／相机 ---------------------

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    // [self.imageButton setImage:resultImage forState:UIControlStateNormal];
    
    
    self.image = resultImage;
    self.imgHead.image = resultImage;
    
    //    self.shoppicImage.image = resultImage;
    //self.headImage.image = resultImage;
  //  [self.imgButton setImage:resultImage forState:UIControlStateNormal];
    
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(100 ,100)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}
- (void)dismissContactView {
    [grayView removeFromSuperview];
}

#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    if (textField == _shoujiTF) {
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    if (textField == self.timeField) {
        return NO;
        
    }
    
//    if (textField == _YZMTextF) {
//        
//        if (string.length == 0) return YES;
//        
//        NSInteger existedLength = textField.text.length;
//        NSInteger selectedLength = range.length;
//        NSInteger replaceLength = string.length;
//        
//        if (existedLength - selectedLength + replaceLength > 4) {
//            return NO;
//        }
//    }
//    
//    
//    NSCharacterSet *cs;
//    
//    if (textField == _passTF ) {
//        
//        cs = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
//        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
//        BOOL basicTest = [string isEqualToString:filtered];
//        if(!basicTest)  {
//            return NO;
//        }
//        
//        if (string.length == 0) return YES;
//        
//        NSInteger existedLength = textField.text.length;
//        NSInteger selectedLength = range.length;
//        NSInteger replaceLength = string.length;
//        
//        if (existedLength - selectedLength + replaceLength > 16) {
//            return NO;
//        }
//    }
    
    return YES;
}
- (IBAction)changePhone:(UIButton *)sender {
    
//    personChangePhoneViewController *vc = [[personChangePhoneViewController alloc] init];
//    
//    if ([[self.dataDic objectForKey:@"userPhone"]length] == 0) {
//        vc.type = @"2";
//    }else {
//    
//        vc.type = @"1";
//        
//    }
//    
//    
//    [self.navigationController pushViewController:vc animated:YES];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
